#!/bin/sh
set -e

chown -R redis:redis /data /var/log/redis

# first arg is `-f` or `--some-option`
# or first arg is `something.conf`
if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then
    set -- redis-server "$@"
fi

if [ "$1" = 'redis-server' ] && [ "$(id -u)" = '0' ]; then
    # first boot
    if [ ! -f /data/dump.rdb ]; then
        if [ -z "$REDIS_PASSWORD" ]; then
            export REDIS_PASSWORD="$(pwgen 32 1)"
            echo "[INFO] Generated Redis Password: $REDIS_PASSWORD"
        fi
        # do not use of -i in sed to save change
        sed "s/^# requirepass foobared$/requirepass $REDIS_PASSWORD/" /etc/redis.conf > /tmp/redis.conf
        cat /tmp/redis.conf > /etc/redis.conf
        rm /tmp/redis.conf
    fi

    set -- su-exec redis "$@"
fi

exec "$@"
